package com.itcanteen.reggie.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itcanteen.reggie.common.R;
import com.itcanteen.reggie.entity.Employee;
import com.itcanteen.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * @author baimugudu
 * @email 2415621370@qq.com
 * @date 2022/10/22 10:05
 */

@RestController
@RequestMapping("/employee")
@Slf4j
public class EmployeeController {


    @Autowired
    EmployeeService employeeService;


    @PostMapping
    public R save(@RequestBody Employee employee,HttpSession httpSession){
        log.info("employee:{}",JSON.toJSONString(employee));
        Long userId = (Long)httpSession.getAttribute("user");
        employee.setCreateUser(userId);
        employee.setUpdateUser(userId);

        employeeService.save(employee);

        return R.success("添加成功");
    }


    @PostMapping("/login")
    public R login(@RequestBody Employee employee, HttpSession session){
        R<Employee> employeeR = employeeService.login(employee);

        //2. 判断是否登录成功，登录成功需要在session中做一个登录成功标记
        if(employeeR.getCode()==1){
            session.setAttribute("user",employeeR.getData().getId());
        }
        //3. 返回给前端
        return employeeR;
    }


    @GetMapping("/page")
    public R page(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer pageSize, String name){
        Page<Employee> employeePage = employeeService.findPage(page, pageSize, name);
        return R.success(employeePage);
    }



    /**
     * 作用： 用户退出
     * 用户退出有两种方案：
     *      1. 从session中清除登录成功标记    session.removeAttribute("user");
     *      2. 直接删除session。   session.invalidate();   建议，因为删除session可以释放内存
     *
     */
    @PostMapping("/logout")
    public R logout(HttpSession session){
        session.invalidate();
        return R.success("退出登录");
    }

    /**
     * 作用：修改员工信息
     */
    @PutMapping
    public R  updateEmp(@RequestBody Employee employee,HttpSession session){
        //补全修改人
        //1.先从session中取出当前登录的用户
        Long empId = (Long) session.getAttribute("user");
        //2. 补全员工的创建人与修改人
        employee.setUpdateUser(empId);
        employeeService.updateEmp(employee);
        return R.success("修改成功");
    }

    /**
     * 作用：根据id查询员工的信息
     */
    @GetMapping("/{id}")
    public R  findById(@PathVariable  Long id){
        Employee employee =  employeeService.findById(id);
        return R.success(employee);
    }

}
